package com.qf.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.qf.aop.IsLogin;
import com.qf.entity.*;
import com.qf.result.ResultMsg;
import com.qf.service.IAddressService;
import com.qf.service.ICartService;
import com.qf.service.IOrderDetailsService;
import com.qf.service.IOrderService;
import com.qf.utils.OrderUtils;
import lombok.extern.slf4j.Slf4j;
import org.omg.CORBA.PRIVATE_MEMBER;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author：刘亚康
 * @Date：2020/4/11
 * @QQ：50770284
 * @Phone：18235947935
 * @Desc : 订单Controller
 **/
@Controller
@Slf4j
@RequestMapping("order")
public class OrderController {

    @Reference
    private IAddressService addressService;

    @Reference
    private ICartService cartService;

    @Reference
    private IOrderService orderService;

    @Autowired
    private OrderUtils orderUtils;

    @Reference
    private IOrderDetailsService orderDetailsService;

    /**
     * 用户由购物车选中要购买的商品跳转到订单确认页面
     * @param cartIdList
     * @param user
     * @param map
     * @return
     */
    @RequestMapping("affirmOrder")
    @IsLogin(mustLogin = true)
        public String affirmOrder(@RequestParam("cartId") List<Integer> cartIdList, User user, ModelMap map){
        System.out.println("OrderController.affirmOrder");
        log.info("用户提交订单"+cartIdList.toString());
        //1：获取用户要下单的购物车
        List<Cart> cartList=cartService.getCartByUserId(cartIdList,user);
        BigDecimal bigDecimal=new BigDecimal(0);
        for (Cart cart1 : cartList) {
            bigDecimal=bigDecimal.add(cart1.getGoodsSubtotal());
        }
        //2：获取用户所有地址
        List<Address> addressList=addressService.getAddressListByUserId(user);
        map.put("cartList",cartList);
        map.put("addressList",addressList);
        map.put("goodsSumSubtotal",bigDecimal);
        return "affirmOrderPage";
    }

    /**
     * 添加用户地址
     * @param user
     * @param address
     * @return
     */
    @RequestMapping("addAddress")
    @IsLogin(mustLogin = true)
    @ResponseBody
    public ResultMsg addAddress(User user,Address address ){
        log.info("添加的地址："+address);
        String result= "";
        int resultAdd=addressService.insertAdd(user,address);
        if (resultAdd>0) {
            return ResultMsg.successMsg("添加成功");
        }else {
            return ResultMsg.fail("添加失败");
        }

    }

    /**
     * 获取用户要编辑的地址
     * @param user
     * @param addressId
     * @return
     */
    @RequestMapping("getEditAddress/{addressId}")
    @IsLogin(mustLogin = true)
    public String getEditAddress(User user, @PathVariable("addressId")Integer addressId,ModelMap map){
        log.info("用户要编辑的地址"+addressId);
        Address address = addressService.getById(addressId);
        map.put("address",address);
        return "address-edit";
    }

    /**
     * 修改用户地址
     * @param user
     * @param address
     * @return
     */
    @ResponseBody
    @IsLogin(mustLogin = true)
    @RequestMapping("editAddress")
    public ResultMsg editAddress(User user,Address address,Integer updateAfterStatusIsDefault){
        log.info("用户要修改的地址为："+address);
        int updateResult=addressService.updateAddress(user,address,updateAfterStatusIsDefault);
        if (updateResult>0) {
            return ResultMsg.successMsg("修改成功");
        }else {
            return ResultMsg.fail("未知原因修改失败，请重试");
        }
    }

    /**
     * 根据Id删除用户地址
     * @param user
     * @param addressId
     * @return
     */
    @ResponseBody
    @RequestMapping("delAddress/{addressId}")
    @IsLogin(mustLogin = true)
    public ResultMsg delAddress(User user, @PathVariable("addressId")Integer addressId){
        int deleteResult=addressService.deleteAddress(addressId,user);
        if (deleteResult>0) {
            return ResultMsg.successMsg("删除成功");
        }else {
            return ResultMsg.fail("未知原因删除失败，请重试");
        }
    }

    /**
     * 用户提交订单
     * @param user
     * @param addressId
     * @param cartIdList
     * @param orderSum
     * @return
     */
    @RequestMapping("orderSubmit")
    @IsLogin(mustLogin = true)
    public String addOrder(User user,Integer addressId,@RequestParam("cartId[]")List<Integer> cartIdList,Integer orderSum){
        log.info("选择的地址"+addressId);
        log.info("选择的购物车Id"+cartIdList.toString());
        log.info("商品总价"+orderSum);
        Order order = new Order();
        //获取地址信息
        Address address = addressService.getById(addressId);
        List<Cart> cartList = cartService.getCartByUserId(cartIdList, user);

        //1:生成订单
        String orderId = orderUtils.createOrderId(user.getUserId());
        order.setOrderId(orderId);
        order.setOrderSum(BigDecimal.valueOf(orderSum));
        order.setOrderState(0);
        order.setAddressId(addressId);
        order.setUserId(user.getUserId());
        order.setConsignee(address.getConsignee());

        orderService.add(order);
        log.info("订单添加成功");

        //2：生成订单详情
        List<OrderDetails> orderDetailsList=new ArrayList<>();
        int insertOrderDetailsResult=0;
        for (Cart cart : cartList) {
            OrderDetails orderDetails=new OrderDetails();
            orderDetails.setOrderId(orderId);
            orderDetails.setGoodsId(cart.getGoodsId());
            String goodsName = cart.getGoods().getGoodsName();
            System.out.println(goodsName);
            orderDetails.setGoodsName(goodsName);
            orderDetails.setGoodsPrice(cart.getGoods().getGoodsPrice());
            orderDetails.setGoodsCount(cart.getGoodsCount());
            orderDetails.setGoodsSubtotal(cart.getGoodsSubtotal());
            orderDetails.setGoodsPic(cart.getGoods().getGoodsPic());
            orderDetails.setGoodsDesc(cart.getGoods().getGoodsDesc());

            orderDetailsList.add(orderDetails);

            if (orderDetailsList.size()==300) {
                insertOrderDetailsResult=insertOrderDetailsResult+orderDetailsService.insertOrderDetailsList(orderDetailsList);
                orderDetailsList.clear();
            }
        }
        if (!orderDetailsList.isEmpty()) {
            insertOrderDetailsResult=insertOrderDetailsResult+orderDetailsService.insertOrderDetailsList(orderDetailsList);
        }
        log.info("订单详情添加成功");

        //3:购物车中删除已经购买的商品
        int delectCart= 0;
        for (Cart cart : cartList) {
            delectCart = cartService.delete(cart.getCartId());
        }
        log.info("删除购物车中已购买的商品成功");
        //4:跳转到支付页面


        return "redirect:http://localhost:8088/pay?orderId="+orderId+"&subtotal="+orderSum.toString();
    }
}
